<?php
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2016/9/18
 * Time: 11:52
 */

namespace app\manage\controller;
class WeixinMsgMenu extends Base
{
//前置操作定义
    protected $beforeActionList = [
        // 'second' =>  ['except'=>'hello'],
        'beforeEdit'  =>  ['only'=>'edit,add'],
    ];
    private $mod;
    public function _initialize(){
        parent::_initialize();
        $this->mod = model('weixin_msg_menu');
    }
    public function index() {
        $tree = new \org\Tree();
        $tree->icon = ['│ ','├─ ','└─ '];
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $result = $this->mod->order('ordid desc,id asc')->select();
        $result = objToArray($result);
        $array = [];
        foreach($result as $r) {
            $r['str_status'] = '<img data-tdtype="toggle" data-id="'.$r['id'].'" data-field="status" data-value="'.$r['status'].'" src="/static/manage/images/toggle_' . ($r['status'] == 0 ? 'disabled' : 'enabled') . '.gif" />';
            $r['str_manage'] = '<a href="'.url('add',['pid'=>$r['id']]).'" class="" data-title="添加子栏目" data-id="add" data-width="500" data-height="360">添加子菜单</a> |
                                <a href="'.url('edit',['id'=>$r['id']]).'" class="" data-title="编辑-'. $r['name'] .'" data-id="edit" data-width="500" data-height="360">编辑</a> |
                                <a href="javascript:;" class="J_confirmurl" data-acttype="ajax" data-uri="'.url('delete',['id'=>$r['id']]).'" data-msg="'.sprintf('确定要删除么？',$r['name']).'">删除</a>';
            $r['parentid_node'] = ($r['pid'])? ' class="child-of-node-'.$r['pid'].'"' : '';

            $array[] = $r;
        }
        $str  = "<tr id='node-\$id' \$parentid_node>
                <td align='center'>\$id</td>
                <td>\$spacer<span data-tdtype='edit' data-field='name' data-id='\$id' class='tdedit'>\$name</span></td>
				<td align='center'>\$type</td>
				<td>\$url</td>
				<td align='center'>\$alias</td>
                <td align='center'><span data-tdtype='edit' data-field='ordid' data-id='\$id' class='tdedit'>\$ordid</span></td>

                <td align='center'>\$str_status</td>
                <td align='center'>\$str_manage</td>
                </tr>";
        $tree->init($array);
        $list = $tree->get_tree(0, $str);
        $this->assign('list', $list);
        $this->assign('list_table', true);
       return $this->fetch();
    }
    protected function beforeEdit(){
        $pid = input('param.pid/d');
        $spid = 0;
        if ($pid) {
            $spid = $this->mod->where(['id'=>$pid])->value('spid');
            $spid = $spid ? $spid.$pid : $pid;
        }
        $this->assign('typeArr',$this->mod->menuType());
        $this->assign('spid', $spid);
    }
    public function addDo(){
        //注册前置事件 只对模型调用
        \app\manage\model\WeixinMsgMenu::event('before_insert',function($obj){
            if(!$this->mod->checkMenuLen($obj->pid)){
                $this->ajaxReturn(0,'一级菜单不能超过3个，该一级菜单下的二级菜单不能超过5个');
            }
            if($obj->pid !=0 && $obj->getData('type') == '0'){
                $this->ajaxReturn(0,'请选择菜单事件');
            }
            //检测分类是否存在
            if($this->mod->name_exists($obj->name, $obj->pid)){
                $this->ajaxReturn(0, '菜单名称已存在');
            }
            //生成spid
            $obj->spid = $this->mod->get_spid($obj->pid);
            if($obj->getData('type') !=0 && $obj->getData('type') != 'view' && empty($obj->alias)){
                $this->ajaxReturn(0,'请填写菜单别名');
            }
            if($obj->getData('type') == 'view'){
                if(!isUrl($obj->url)){
                    $this->ajaxReturn(0,'请填写正确的链接地址,以"http://或https://"开头');
                }
            }
            if ($this->mod->name_exists($obj->alias, 0,'alias')) {
                $this->ajaxReturn(0, '菜单别名已存在');
            }
            return true;
        });
        parent::addDo();
    }
    public function editDo(){
        \app\manage\model\WeixinMsgMenu::event('before_update',function($obj){
            if($obj->pid !=0 && $obj->getData('type') == '0'){
                $this->ajaxReturn(0,'请选择菜单事件');
            }
            //检测分类是否存在
            if($this->mod->name_exists($obj->name, $obj->pid,'name',$obj->id)){
                $this->ajaxReturn(0, '菜单名称已存在');
            }
            if ($this->mod->name_exists($obj->alias, 0,'alias',$obj->id)) {
                $this->ajaxReturn(0, '菜单别名已存在');
            }
            return true;
        });
        parent::editDo();
    }
    public function delete(){
        //判断是否有下级栏目存在  存在则不能删除
        \app\manage\model\WeixinMsgMenu::event('before_delete',function($obj){
            $id = $obj->id;
            //是否有下级栏目
            $child = $this->mod->get_child_ids($id);
            if(!empty($child)){
                $this->error = '该菜单下还存在子菜单不能被删除';
                return false;
            }
            return true;
        });
        parent::delete();
    }

    /**
     * 创建微信菜单
     */
    public function create(){
        $lists = $this->mod->field('id,pid,alias,name,type,url')->where(['status'=>1])->order('ordid asc')->select();
        if($lists){
           $data = $this->_getMenuData($lists);
            $menu['button'] = $data;
            $obj = controller('manage/Weixin','event');
            $obj->init('Menu');
            $return = $obj->createMenu($menu);//上传到微信服务器
            if($return['errcode'] == 0){
                $this->ajaxReturn(1,'创建菜单成功');
            }else{
                $this->ajaxReturn(0,$return['errmsg']);
            }
        }else{
            $this->ajaxReturn(0,'请先添加菜单后再发送到微信');
        }

    }
    private function _getMenuData($lists){
        $first = [];
        $tmp   = [];
        foreach($lists as $key=>&$v){
            $v['event'] = $v->getData('type');
            if($v['pid'] == 0){
                $first[$v['id']] = $v->toArray();
                unset($lists[$key]);
            }else{
                continue;
            }
        }
        $lists = objToArray($lists);
        foreach($first as $k=>&$val){
            foreach($lists as $two=>$second){
                if($k == $second['pid']){
                    $event     = $second['event'] == 'view' ? 'url' : 'key';
                    $event_val = $second['event'] == 'view' ? $second['url'] : $second['alias'];
                    $val['sub_button'][] = [
                        'name' => $second['name'],
                        'type' => $second['event'],
                        $event => $event_val
                    ];
                }else{
                    continue;
                }
            }
            //$data[$k] = &$val;
            if(!isset($val['sub_button'])){
                $event     = $val['event'] == 'view' ? 'url' : 'key';
                $event_val = $val['event'] == 'view' ? $val['url'] : $val['alias'];
                $tmp[] = [
                    'name' => $val['name'],
                    'type' => $val['event'],
                    $event => $event_val
                ];
            }else{
                $tmp[] = [
                    'name' => $val['name'],
                    'sub_button' => $first[$k]['sub_button']
                ];
            }
        }
        return $tmp;
    }
    public function ajaxGetchilds() {
        $id = input('param.id/d');
        $return = $this->mod->field('id,name')->where(['pid'=>$id])->select();
        if ($return) {
            $this->ajaxReturn(1, 'success', $return);
        } else {
            $this->ajaxReturn(0, 'error');
        }
    }

}